package com.yejq.db;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yejq.Constants;
import com.yejq.util.PropertiesUtils;

/**
 * db的后台服务程序
 * @author yejq
 */
public class Bingbingdbd {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@SuppressWarnings("unchecked")
	public void startServer(int port){
		ServerSocket server = null;
		try {
			server = new ServerSocket(port);
			logger.info("welcome to bingbingdb, server is started! port:{}",  PropertiesUtils.getInt(Constants.KEY_PORT));
			while (true) {
				Socket socket = server.accept();
				Class<Processor> clazz = (Class<Processor>)Class.forName(PropertiesUtils.getString("processor"));
				Constructor<Processor> constructor = clazz.getConstructor(Socket.class);
				Processor processor = constructor.newInstance(socket);
				new Thread(processor).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if (server != null) {
					server.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		new Bingbingdbd().startServer(PropertiesUtils.getInt(Constants.KEY_PORT));
	}


}
